#include "Moto.h"
#include "../TinyXML/tinyxml.h"
#include "../ChineseEnglishMapping.h"
#include <QDebug>
#include <QVBoxLayout>
#include <QSplitter>

Moto::Moto()
{

}

void Moto::InitUI(const QString &fileName, QList<QPair<QWidget *, QString> > &widgets, QMap<int, QList<TableWidgetForm *> > &m_pTableWidgetFormMap)
{
    QString filePath = QString("%1/config/%2/%3")
            .arg(COMMONS->XmlPath)
            .arg(COMMONS->MachType)
            .arg(fileName);
    MotoConnectStr _ConnectStr;
    QList<MotoMotoStruct> _MotoStructs;
    Analysis(filePath, _ConnectStr, _MotoStructs);

    //添加第一个表
    QWidget* widget = new QWidget;
    QVBoxLayout *layout = new QVBoxLayout(widget);
    QSplitter *splitter = new QSplitter(Qt::Vertical, widget);
    splitter->setChildrenCollapsible(false);
    layout->addWidget(splitter);
    widgets.append(qMakePair(widget,QStringLiteral("tab0")));

    TableWidgetForm* _TableWidgetForm = new TableWidgetForm(widget);
    splitter->addWidget(_TableWidgetForm);
    _TableWidgetForm->setGroupBoxTitle(QString("%1_0").arg(fileName.left(fileName.size()-4)));

    //获取表头
    _TableWidgetForm->setTableWidgetHeaderLabels(COMMONS->getTableWidgetHeadLabels(fileName,_ConnectStr.toFieldNames().split(',')));
    _TableWidgetForm->setTableWidgetHeaderType(_ConnectStr.toFieldTypes());

    _TableWidgetForm->getTableWidget()->setRowCount(1);
    _TableWidgetForm->getTableWidget()->setItem(0, 0, new QTableWidgetItem(_ConnectStr.name));
    _TableWidgetForm->getTableWidget()->setItem(0, 1, new QTableWidgetItem(_ConnectStr.type));

    //添加第二个表
    TableWidgetForm* _TableWidgetForm2 = new TableWidgetForm(widget);
    splitter->addWidget(_TableWidgetForm2);
    _TableWidgetForm2->setGroupBoxTitle(QString("%1_1").arg(fileName.left(fileName.size()-4)));

    if (_MotoStructs.size() > 0)
    {
        MotoMotoStruct _motoStruct;
        //获取表头
        _TableWidgetForm2->setTableWidgetHeaderLabels(COMMONS->getTableWidgetHeadLabels(fileName, _motoStruct.toFieldNames().split(',')));

        for(int i = 0;i<_MotoStructs.size();i++)
        {
            int rowCount = _TableWidgetForm2->getTableWidget()->rowCount();
            _TableWidgetForm2->getTableWidget()->setRowCount(rowCount+1);
            _TableWidgetForm2->getTableWidget()->setItem(rowCount, 0, new QTableWidgetItem(_MotoStructs.at(i).name));
            _TableWidgetForm2->getTableWidget()->item(rowCount,0)->setData(Qt::UserRole,_MotoStructs.at(i).id);
            _TableWidgetForm2->getTableWidget()->setItem(rowCount, 1, new QTableWidgetItem(QString("%1").arg(_MotoStructs.at(i).currentlocation)));
            _TableWidgetForm2->getTableWidget()->setItem(rowCount, 2, new QTableWidgetItem(QString("%1").arg(_MotoStructs.at(i).speed)));
            _TableWidgetForm2->getTableWidget()->setItem(rowCount, 3, new QTableWidgetItem(QString("%1").arg(_MotoStructs.at(i).maxspeed)));
            _TableWidgetForm2->getTableWidget()->setItem(rowCount, 4, new QTableWidgetItem(QString("%1").arg(_MotoStructs.at(i).board_id)));
            _TableWidgetForm2->getTableWidget()->setItem(rowCount, 5, new QTableWidgetItem(QString("%1").arg(_MotoStructs.at(i).phyid)));
            _TableWidgetForm2->getTableWidget()->setItem(rowCount, 6, new QTableWidgetItem(QString("%1").arg(_MotoStructs.at(i).enable)));
        }
    }
    m_pTableWidgetFormMap.insert(0,  QList<TableWidgetForm*>() << _TableWidgetForm << _TableWidgetForm2);
}

bool Moto::SaveUI(const QString &fileName, const QMap<int, QList<TableWidgetForm *> > &m_pTableWidgetFormMap)
{
    QString filePath = QString("%1/config/%2/%3")
            .arg(COMMONS->XmlPath)
            .arg(COMMONS->MachType)
            .arg(fileName);
    if(m_pTableWidgetFormMap.count() == 1 && m_pTableWidgetFormMap.value(0).size() == 2)
    {
        MotoConnectStr _ConnectStr;
        QList<MotoMotoStruct> _MotoStructs;

        TableWidgetForm* _TableWidgetForm = m_pTableWidgetFormMap.value(0).at(0);
        if(_TableWidgetForm)
        {
            _ConnectStr.name = _TableWidgetForm->getTableWidget()->item(0, 0)->text();
            _ConnectStr.type = _TableWidgetForm->getTableWidget()->item(0, 1)->text();
        }

        TableWidgetForm* _TableWidgetForm2 = m_pTableWidgetFormMap.value(0).at(1);
        if(_TableWidgetForm2)
        {
            for (int k = 0;k<_TableWidgetForm2->getTableWidget()->rowCount();k++)
            {
                MotoMotoStruct _MotoStruct;
                _MotoStruct.id = _TableWidgetForm2->getTableWidget()->item(k,0)->data(Qt::UserRole).toInt();
                _MotoStruct.name = _TableWidgetForm2->getTableWidget()->item(k,0)->text();
                _MotoStruct.currentlocation = _TableWidgetForm2->getTableWidget()->item(k,1)->text().toInt();
                _MotoStruct.speed = _TableWidgetForm2->getTableWidget()->item(k,2)->text().toInt();
                _MotoStruct.maxspeed = _TableWidgetForm2->getTableWidget()->item(k,3)->text().toInt();
                _MotoStruct.board_id = _TableWidgetForm2->getTableWidget()->item(k,4)->text().toInt();
                _MotoStruct.phyid = _TableWidgetForm2->getTableWidget()->item(k,5)->text().toInt();
                _MotoStruct.enable = _TableWidgetForm2->getTableWidget()->item(k,6)->text().toInt();
                _MotoStructs.append(_MotoStruct);
            }
        }
        SaveXml(filePath,_ConnectStr,_MotoStructs);
        return true;
    }
    return false;
}

void Moto::Analysis(const QString &path, MotoConnectStr &strs, QList<MotoMotoStruct> &motos)
{
    TiXmlDocument* xmlDocument = new TiXmlDocument();
    if(!xmlDocument->LoadFile(path.toStdString().c_str()))
    {
        qDebug() << xmlDocument->ErrorDesc();
        delete xmlDocument;
        return;
    }

    TiXmlElement* rootElement = xmlDocument->FirstChildElement("Motos");
    if(rootElement == nullptr) //节点不存在
    {
        qDebug() << xmlDocument->ErrorDesc();
        delete xmlDocument;
        return;
    }

    if(rootElement)
    {
        TiXmlElement* ConnectStrElement = rootElement->FirstChildElement("ConnectStr");
        if(ConnectStrElement != nullptr)
        {
            strs.name = ConnectStrElement->Attribute("name");
            strs.type = ConnectStrElement->Attribute("type");
        }

        TiXmlElement* GroupElement = rootElement->FirstChildElement("Group");
        if(GroupElement != nullptr)
        {
            TiXmlElement* SubGroupElement = GroupElement->FirstChildElement("SubGroup");
            if(SubGroupElement != nullptr)
            {
                for (TiXmlElement* MotoElement = SubGroupElement->FirstChildElement("Moto");
                     MotoElement != nullptr; MotoElement = MotoElement->NextSiblingElement("Moto")) {
                    if(MotoElement != nullptr)
                    {
                        MotoMotoStruct _moto;
                        MotoElement->QueryIntAttribute("id", &_moto.id);
                        _moto.name = MotoElement->Attribute("name");
                        MotoElement->QueryIntAttribute("currentlocation", &_moto.currentlocation);
                        MotoElement->QueryIntAttribute("speed", &_moto.speed);
                        MotoElement->QueryIntAttribute("maxspeed", &_moto.maxspeed);
                        MotoElement->QueryIntAttribute("board_id", &_moto.board_id);
                        MotoElement->QueryIntAttribute("phyid", &_moto.phyid);
                        MotoElement->QueryIntAttribute("enable", &_moto.enable);
                        motos.append(_moto);
                    }
                }
            }
        }
    }

    delete xmlDocument;
}

bool Moto::SaveXml(const QString &path, const MotoConnectStr &str, const QList<MotoMotoStruct> &motos)
{
    TiXmlDocument* xmlDocument = new TiXmlDocument();
    if(!xmlDocument->LoadFile(path.toStdString().c_str()))
    {
        qDebug() << xmlDocument->ErrorDesc();
        delete xmlDocument;
        return false;
    }

    //查找xml文件中第一个名为Person的节点
    TiXmlElement* rootElement = xmlDocument->FirstChildElement("Motos");
    if(rootElement == nullptr) //节点不存在
    {
        qDebug() << xmlDocument->ErrorDesc();
        delete xmlDocument;
        return false;
    }

    if(rootElement)
    {
        TiXmlElement* ConnectStrElement = rootElement->FirstChildElement("ConnectStr");
        if(ConnectStrElement != nullptr)
        {
            ConnectStrElement->SetAttribute("name", str.name.toStdString().c_str());
            ConnectStrElement->SetAttribute("type", str.type.toStdString().c_str());
        }

        TiXmlElement* GroupElement = rootElement->FirstChildElement("Group");
        if(GroupElement != nullptr)
        {
            TiXmlElement* SubGroupElement = GroupElement->FirstChildElement("SubGroup");
            if(SubGroupElement != nullptr)
            {
                for (TiXmlElement* MotoElement = SubGroupElement->FirstChildElement("Moto");
                     MotoElement != nullptr; MotoElement = MotoElement->NextSiblingElement("Moto")) {
                    if(MotoElement != nullptr)
                    {
                        SubGroupElement->RemoveChild(MotoElement);
                    }
                }
                for (auto _MotoStruct : motos)
                {
                    //元素类
                    TiXmlElement* ChildxmlElement = new TiXmlElement("Moto");
                    ChildxmlElement->SetAttribute("id", _MotoStruct.id);
                    ChildxmlElement->SetAttribute("name", _MotoStruct.name.toStdString().c_str());
                    ChildxmlElement->SetAttribute("currentlocation", _MotoStruct.currentlocation);
                    ChildxmlElement->SetAttribute("speed", _MotoStruct.speed);
                    ChildxmlElement->SetAttribute("maxspeed", _MotoStruct.maxspeed);
                    ChildxmlElement->SetAttribute("board_id", _MotoStruct.board_id);
                    ChildxmlElement->SetAttribute("phyid", _MotoStruct.phyid);
                    ChildxmlElement->SetAttribute("enable", _MotoStruct.enable);
                    SubGroupElement->LinkEndChild(ChildxmlElement);
                }
            }
        }
    }

    //保存
    xmlDocument->SaveFile(path.toStdString().c_str());

    delete xmlDocument;
    return true;
}
